const {
	log
} = require("util");

module.exports = {
	/**
	 * 查询多条记录 分页
	 * @url admin/pages/kh/tjsj/Regeanalysis/getList  前端调用的url参数地址
	 * data 请求参数 说明
	 * @params {Number}         pageIndex 当前页码
	 * @params {Number}         pageSize  每页显示数量
	 * @params {object}         formData  查询条件数据源
	 * res 返回参数说明
	 * @params {Number}         code      错误码，0表示成功
	 * @params {String}         msg       详细信息
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			formData,
			date
		} = data;
		let res = {
			code: 0,
			msg: ''
		};
		let startTime = formData.date[0] ? formData.date[0] : null
		let endTime = formData.date[1] ? formData.date[1] : null
		const dateRange = getDatesBetween(startTime, endTime);
		let tv_id = formData.tv_id
		let tv_name = formData.tv_name
		const vipHistoryFilter = {
			_add_time: {
				$gte: new Date(startTime),
				$lte: new Date(endTime)
			},
			tv_id,
			tv_name
		};
		// 1. 根据条件筛选出 a_vip_history 表中的用户观看记录（去重后的）
		const vipHistoryRes = await vk.baseDao.getTableData({
			dbName: 'a_vip_history',
			filter: vipHistoryFilter,
			distinct: ['tv_id', 'user_id'],
			group: ['tv_id', 'user_id'],
		});

		const vipHistory = vipHistoryRes.rows;
		const uniqueUserIds = new Set(vipHistory.map(record => record.user_id));

		// 2. 根据去重后的用户 ID 查找 uni-id-users 表中的注册时间
		const usersRes = await vk.baseDao.getTableData({
			dbName: 'uni-id-users',
			filter: {
				_id: {
					$in: Array.from(uniqueUserIds)
				}
			}
		});

		const users = usersRes.rows.reduce((acc, user) => {
			acc[user._id] = user.register_date;
			return acc;
		}, {});

		// 3. 查找 a_had_pay 表中的充值记录
		const payHistoryRes = await vk.baseDao.getTableData({
			dbName: 'a_had_pay',
			filter: {
				user_id: {
					$in: Array.from(uniqueUserIds)
				}
			}
		});

		const payHistory = payHistoryRes.rows;

		// 4. 处理数据
		const dramas = dateRange.map(date => {
			const dailyDrama = {
				date: date,
				tv_name: "",
				tv_id: tv_id,
				watchCount: 0,
				firstChargeUsers: new Set(),
				firstChargeAmount: 0,
				secondChargeUsers: new Set(),
				secondChargeAmount: 0,
				thirdChargeUsers: new Set(),
				thirdChargeAmount: 0,
				totalAmount: 0
			};
			vipHistory.forEach(record => {
				if (new Date(record._add_time).toISOString().slice(0, 10) === date) {
					dailyDrama.watchCount++;

					const user_id = record.user_id;
					const userPayHistory = payHistory.filter(p => p.user_id === user_id && p
						.tv_id === tv_id);
					const chargeCount = userPayHistory.length;

					if (users[user_id] && new Date(users[user_id]).getTime() >= startTime &&
						new Date(users[user_id]).getTime() <= endTime) {
						if (chargeCount > 0) {
							dailyDrama.firstChargeUsers.add(user_id);
							dailyDrama.firstChargeAmount += userPayHistory[0].pay_amount;
						}
						if (chargeCount > 1) {
							dailyDrama.secondChargeUsers.add(user_id);
							dailyDrama.secondChargeAmount += userPayHistory[1].pay_amount;
						}
						if (chargeCount > 2) {
							dailyDrama.thirdChargeUsers.add(user_id);
							dailyDrama.thirdChargeAmount += userPayHistory[2].pay_amount;
						}
						dailyDrama.totalAmount += userPayHistory.reduce((sum, record) => sum +
							record.pay_amount, 0);
					}
				}
			});

			// 计算统计信息
			const watchCount = dailyDrama.watchCount;

			dailyDrama.firstChargeUsers = dailyDrama.firstChargeUsers.size;
			dailyDrama.firstChargeRate = (dailyDrama.firstChargeUsers / watchCount) * 100;
			dailyDrama.secondChargeUsers = dailyDrama.secondChargeUsers.size;
			dailyDrama.secondChargeRate = (dailyDrama.secondChargeUsers / watchCount) * 100;
			dailyDrama.thirdChargeUsers = dailyDrama.thirdChargeUsers.size;
			dailyDrama.thirdChargeRate = (dailyDrama.thirdChargeUsers / watchCount) * 100;
			dailyDrama.avgUserCharge = watchCount > 0 ? dailyDrama.totalAmount / watchCount : 0;
			dailyDrama.avgUserPayAmount = watchCount > 0 ? dailyDrama.totalAmount / watchCount : 0;

			return dailyDrama;
		});

		return {
			status: 0,
			data: dramas
		};


		function getDatesBetween(startDate, endDate) {
			const dates = [];
			const start = new Date(startDate);
			const end = new Date(endDate);
			let currentDate = start;

			while (currentDate <= end) {
				dates.push(currentDate.toISOString().slice(0, 10));
				currentDate.setDate(currentDate.getDate() + 1);
			}

			return dates;
		}
	}
}